package com.holly.common_view.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.ColorInt;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.holly.common_view.R;
import com.holly.common_view.utils.DensityUtils;

/**
 * 限制字符输入长度的组合控件
 * <p>
 * <p>
 * 2017/2/28 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
public class LimitLengthEditLayout extends LinearLayout {
    private TextView mTvHint;
    private EditText mEtContent;
    private int mMaxLength = 100;//默认100
    private int mCurrLength = 0;
    private int mEditTextColor = Color.parseColor("#616161");
    private int mEditTextHintColor = Color.parseColor("#757575");
    private int mStrokeColor = Color.parseColor("#DDDDDD");
    private int mEditTextSolidColor = Color.WHITE;
    private int mStrokeDpWidth = 1;
    private String mHintText;
    private int mHintTextViewColor = Color.parseColor("#757575");

    private TextWatcher mTextWatcher;

    public LimitLengthEditLayout(Context context) {
        this(context, null);
    }

    public LimitLengthEditLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LimitLengthEditLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LimitLengthEditLayout);
        mHintText = a.getString(R.styleable.LimitLengthEditLayout_hint);
        int maxLength = a.getInt(R.styleable.LimitLengthEditLayout_maxLength, -1);
        if (maxLength > 0) {
            mMaxLength = maxLength;
        }
        a.recycle();
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void initView() {
        //设置布局为线性布局
        setOrientation(VERTICAL);

        int dp5 = DensityUtils.dip2px(getContext(), 5);

        //开始代码生成布局文件
        GradientDrawable editBackground = new GradientDrawable();
        editBackground.setStroke(getStrokeWidth(), mStrokeColor);
        editBackground.setColor(mEditTextSolidColor);
        editBackground.setCornerRadius(dp5);

        //创建控件
        mTvHint = new TextView(getContext());
        mEtContent = new EditText(getContext());

        //设置字体颜色
        mTvHint.setTextColor(mHintTextViewColor);
        mEtContent.setTextColor(mEditTextColor);
        mEtContent.setHintTextColor(mEditTextHintColor);
        //设置字体大小
        mEtContent.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimensionPixelSize(R.dimen.caption));
        mTvHint.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimensionPixelSize(R.dimen.caption_small));

        //设置背景
        mEtContent.setBackground(editBackground);
        //设置编辑框属性
        mEtContent.setMinLines(2);

        //设置文本
        refreshSizeHint();

        LinearLayout.LayoutParams editViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mEtContent.setWidth(Integer.MAX_VALUE);
        mEtContent.setGravity(Gravity.TOP | Gravity.START);
        mEtContent.setPadding(dp5, dp5, dp5, dp5);
        editViewParams.weight = 1;
        addView(mEtContent, editViewParams);

        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textViewParams.gravity = Gravity.RIGHT;
        addView(mTvHint, textViewParams);
        initListener();
        setHint(mHintText);
    }

    //初始化监听
    private void initListener() {
        mEtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (mTextWatcher != null) {
                    mTextWatcher.onTextChanged(s, start, count, after);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = s.toString();
                if (text.length() > mMaxLength) {
                    mEtContent.setText(text.substring(0, text.length() - 1));
                    mEtContent.setSelection(mMaxLength);
                } else {
                    mCurrLength = text.length();
                    refreshSizeHint();
                    if (mTextWatcher != null) {
                        mTextWatcher.onTextChanged(s, start, before, count);
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mTextWatcher != null) {
                    mTextWatcher.afterTextChanged(s);
                }
            }
        });
    }

    /**
     * 设置输入框提示文本
     *
     * @param text 文本内容
     */
    public void setHint(String text) {
        if (TextUtils.isEmpty(text)) {
            mEtContent.setHint("");
        } else {
            mEtContent.setHint(text);
        }
    }

    /**
     * 设置编辑框文本
     *
     * @param text 文本内容
     */
    public void setText(String text) {
        mEtContent.setText(text);
    }

    /**
     * 获取输入的文本内容
     *
     * @return 文本内容
     */
    public String getText() {
        return mEtContent.getText().toString();
    }

    /**
     * 设置文本编辑框最大的长度
     *
     * @param length 最大长度 不能小于1
     */
    public void setMaxLength(int length) {
        if (length < 1) {
            throw new IllegalArgumentException("length can not less than 1");
        }
        mMaxLength = length;
        //最大长度改变，因此删除多余的内容
        String text = mEtContent.getText().toString();
        if (text.length() > mMaxLength) {
            mEtContent.setText(text.substring(0, mMaxLength));
        }
        refreshSizeHint();
    }

    /**
     * 设置编辑框监听
     *
     * @param textWatcher 监听
     */
    public void setTextChangedListener(TextWatcher textWatcher) {
        mTextWatcher = textWatcher;
    }

    /**
     * 设置编辑框监听
     *
     * @param textWatcher 监听
     */
    public void addTextChangedListener(TextWatcher textWatcher) {
        mTextWatcher = textWatcher;
    }

    /**
     * 设置最小的行数
     *
     * @param minLines 最小行数
     */
    public void setMinLines(int minLines) {
        mEtContent.setMinLines(minLines);
    }

    public void setEditTextStrokeColor(@ColorInt int color) {
        GradientDrawable background = (GradientDrawable) mEtContent.getBackground();
        if (background == null) {
            background = new GradientDrawable();
        }
        background.setStroke(getStrokeWidth(), color);
        mEtContent.setBackground(background);
    }

    private int getStrokeWidth() {
        return DensityUtils.dip2px(getContext(), mStrokeDpWidth);
    }

    //刷新提示信息
    private void refreshSizeHint() {
        mTvHint.setText(mCurrLength + "/" + mMaxLength);
    }
}
